package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.User;
import com.weilai.service.UserService;

import com.weilai.util.PasswordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Controller
@Api(tags = "密码登录", description = "提供密码登录方法的接口")
@RequestMapping("/login")
public class LoginPasswordController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "跳转密码登录页面", notes = "在密码登录之前需要判断是否记住密码，这个方法用来判断，" +
            "如果用户选择了记住密码，则会传给前端用户的账号密码，如果没选择就会传两个空字符串")
    @ApiResponses({
            @ApiResponse(code = 200, message = "跳转成功")
    })
    //跳转页面，并判断是否记住密码
    @GetMapping
    public ModelAndView showLoginPage() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("login");
        return mav;
    }

    @ApiOperation(value = "密码登录", notes = "密码登录方法，需要输入用户邮箱和密码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录成功")
    })
    //密码登录
    @PostMapping("/loginPassword")
    public ModelAndView login(@RequestParam String email, @RequestParam String password,
                              HttpServletRequest request) {
        HttpSession session = request.getSession();
        try {
            session.setAttribute("loginPasswordEmail", "");
            session.setAttribute("loginPassword", "");

            User user = userService.getUserByEmail(email);
            ModelAndView mav = new ModelAndView();

            if (user == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "无此用户，请创建用户后再登录");
            }

            // 密码复杂度校验
            if (password.length() < 6 || password.length() > 20) {
                session.setAttribute("loginPasswordEmail", email);
                session.setAttribute("loginPassword", password);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码长度需在6-20位之间");
            }

            boolean hasLetter = password.chars().anyMatch(Character::isLetter);
            if (!hasLetter) {
                session.setAttribute("loginPasswordEmail", email);
                session.setAttribute("loginPassword", password);
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "密码必须包含字母");
            }

//            if (!PasswordUtil.matches(password, user.getPassword())) {
//                session.setAttribute("loginPasswordEmail", email);
//                session.setAttribute("loginPassword", password);
//                throw new BusinessException(Code.PROJECT_BUSINESS_ERROR, "密码错误，请重新输入");
//            }
            if (!password.equals(user.getPassword())) {
                session.setAttribute("loginPasswordEmail", email);
                session.setAttribute("loginPassword", password);
                throw new BusinessException(Code.PROJECT_BUSINESS_ERROR, "密码错误，请重新输入");
            }

            // 登录成功处理
            session.setAttribute("userId", user.getId());
            user.setPassword("****");
            session.setAttribute("user", user);
            if (user.getRole().equals("admin")) {
                mav.setViewName("redirect:/mainPageRecommend");
            } else {
                mav.setViewName("redirect:/mainPageRecommend");
            }

            session.removeAttribute("loginPasswordEmail");
            session.removeAttribute("loginPassword");

            return mav;
        } catch (BusinessException e) {
            session.setAttribute("loginPasswordEmail", email);
            session.setAttribute("loginPassword", password);
            throw e;
        } catch (Exception e) {
            session.setAttribute("loginPasswordEmail", email);
            session.setAttribute("loginPassword", password);
            throw new SystemException(Code.SYSTEM_DB_ERROR, "登录过程中出现系统错误", e);
        }
    }

    @PostMapping("/deleteSession")
    public ModelAndView deleteSession(HttpServletRequest request) {
        HttpSession session = request.getSession();

        //密码登录
        session.removeAttribute("loginPasswordEmail");
        session.removeAttribute("loginPassword");

        //验证码登录
        session.removeAttribute("loginCodeEmail");

        //注册
        session.removeAttribute("registerEmail");
        session.removeAttribute("registerPassword");
        session.removeAttribute("registerUsername");
        session.removeAttribute("registerCode");

        //忘记密码
        session.removeAttribute("forgetPasswordEmail");
        session.removeAttribute("forgetPasswordPassword");
        session.removeAttribute("forgetPasswordCode");

        return new ModelAndView("redirect:/");// 重定向到根路径
    }
}
